package model;

import java.awt.Color;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import interfaces.*;

/**
 * A model of Hunter Hunter can shoot and randomly moves around the field
 * 
 * @author Stephan Veenstra, Marc Bruins, Michel Jansma
 * @version 2012.11.08
 */

public class Hunter implements Actor {

	//Hunter color
	public static Color COLOR = Color.BLACK;
	// A shared random number generator to set location
	protected static final Random rand = Randomizer.getRandom();

	private boolean active;
	private Field field;
	private Location location;

	private static final int TOTALSHOTS = 0;

	public Hunter(Field field, Location location) {
		this.active = true;
		this.field = field;
		this.location = location;
		setLocation();
	}

	/**
	 * Check whether the hunter is alive or not.
	 * @return true if the hunter is still alive.
	 */
	public boolean isActive() {
		return active;
	}

	/**
	 * This is what the hunter does it moves to a new location then shoots animals at that location
	 */
	public void act(List<Actor> newActors) {
		setLocation();
		shootAnimals(this.location);
	}

	/**
	 * getting Adjacentlocations and shoot to the locations next to them.
	 * @param location     Where in the field it is located.
	 */
	private void shootAnimals(Location location) {
		Field field = this.field;
		List<Location> adjacent = field.adjacentLocations(this.location);
		Iterator<Location> it = adjacent.iterator();
		//Amount of shots
		int i = 0;
		for (int k = 0; k < adjacent.size(); k++) {
			if (i < TOTALSHOTS) {
				Location where = it.next();
				Object target = field.getObjectAt(where);
				if (target instanceof Animal) {
					Animal animal = (Animal) target;
					if (animal.isActive()) {
						animal.setDead();
					}
					i++;
				}
			} else {
				k = adjacent.size();
			}
		}
	}

	/*
	 * Set new location for the hunter
	 */

	public void setLocation() {
		try {
			//Don't add new hunter one each step.
			if (location != null) {
				field.clear(location);
			}
			
			Location adjLocation = getNewLocation();
			adjLocation = field.freeAdjacentLocation(adjLocation);
			//if location is null try again
			if (adjLocation == null) {
				setLocation();
			}

			field.place(this, adjLocation);
			this.location = adjLocation;
		} catch (NullPointerException e) {
			//System.out.println("Exception" + e);
		}

	}

	/*
	 * Get a new location Checks if the location is positioned outside of the
	 * field
	 */
	private Location getNewLocation() {
		int x = rand.nextInt(field.getDepth() + 1);
		int y = rand.nextInt(field.getWidth() + 1);
		if (x == 0) {
			x = x + 1;
		}
		if (y == 0) {
			y = y + 1;
		}

		Location newLocation = new Location(x, y);

		return newLocation;
	}
}
